package com.app.config;

import com.alibaba.fastjson.JSON;

import com.app.entity.User;
import com.app.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 效验需要登陆认证的请求
 */
@Slf4j
public class jwtValidityTokenFilter extends BasicAuthenticationFilter {
    private JwtUtil jwtUtil;

    public jwtValidityTokenFilter(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {
        super(authenticationManager);
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //请求体的头中是否包含Authorization
        String header = request.getHeader("token");
        //Authorization中是否包含Bearer，不包含直接返回
        if (header == null || "null".equals(header)) {
            chain.doFilter(request, response);
            return;
        }
        try {
            Claims claims = jwtUtil.parseJWT(header);
            User user = JSON.parseObject(claims.getSubject(), User.class);//自定义
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (Exception e) {
            throw new RuntimeException("token失效");
        }
        //获取后，将Authentication写入SecurityContextHolder中供后序使用
        chain.doFilter(request, response);
    }
}
